package com.helloscala.model

import scala.collection.mutable

import org.bson.types.ObjectId
import org.joda.time.DateTime
import org.squeryl.{Session, KeyedEntity}

import net.liftweb.common.Box

import yangbajing.util.Imports.Y

import MyTypeMode._

class MDocumentComment(val document_id: String,
                    val creator: String,
                    val content: String,
                    val created_at: DateTime = DateTime.now()) extends KeyedEntity[String] with MessageDataTrait {

  val id: String = ObjectId.get.toString
}

object MDocumentComment {

  def findLastByDocumentId(documentId: String, limit: Int): List[MDocumentComment] =
    transaction(from(Entities.documentComments)(ac =>
      where(
        ac.document_id === documentId
      ) select (ac) orderBy (ac.created_at.desc)).page(0, limit).toList)

  def size(documentId: Option[String] = None): Long =
    transaction(from(Entities.documentComments)(ac =>
      where(
        ac.document_id === documentId.?
      ) compute (count(ac.id))))

  def create(documentId: String, author: String, content: String): Box[MDocumentComment] =
    Y.tryBox {
      val am = new MDocumentComment(documentId, author, content)
      transaction {
        val result = Entities.documentComments insert am
        MDocument.incrementById(documentId, 1L)
        result
      }
    }

  def popularDocumentIds(limit: Int): List[String] =
    transaction {
      val conn = Session.currentSession.connection
      val sql = """select ac.ref_id
                  | from document_comment_ ac
                  | group by ac.ref_id
                  | order by count(ac.id) desc
                  | limit ?""".stripMargin
      val pstmt = conn.prepareStatement(sql)
      pstmt.setInt(1, limit)
      val rs = pstmt.executeQuery()
      val buffer = mutable.ArrayBuffer[String]()
      while (rs.next()) {
        buffer += rs.getString(1)
      }
      buffer.toList
    }

  //    MDocument.findAllPopular(limit).map(_.id).toList

}
